package com.azzcs.myrpc.request;

import com.alibaba.fastjson.JSONObject;
import com.azzcs.myrpc.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * @Author: wzg
 * @Date: 2021/1/23 下午9:55
 */

public class RpcDecoder extends ByteToMessageDecoder {

    private static final int HEAD_LENGTH = 4;
    private Serializer serializer;

    public RpcDecoder(Serializer serializer) {
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < HEAD_LENGTH) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (dataLength < 0) {
            ctx.close();
        }
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[dataLength];
        in.readBytes(bytes);
        RpcRequest request = serializer.deserialize(RpcRequest.class, bytes);
        if(request.getParameters().length > 0){
            Class<?>[] parameterTypes = request.getParameterTypes();
            Object[] parameters = request.getParameters();
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = serializer.deserialize(parameterTypes[i],serializer.serialize(parameters[i]));
            }
        }
        out.add(request);
    }
}
